package com.d3works.apps.stock.service;

import com.d3works.apps.stock.db.repo.StockInOutRepository;
import com.d3works.db.JPA;
import com.google.inject.Inject;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.Query;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

public class StockMoveStatisticServiceImpl implements StockMoveStatisticService {
  protected StockInOutRepository stockInOutRepository;

  @Inject
  public StockMoveStatisticServiceImpl(StockInOutRepository stockInOutRepository) {
    this.stockInOutRepository = stockInOutRepository;
  }

  @Override
  public Object getInOutStatsticData(
      String beginDate, String endDate, Object locationId, Object productId) throws Exception {
    List<Object> args = new ArrayList<>();
    List<String> conds = new ArrayList<>();

    if (StringUtils.isNotEmpty(beginDate)) {
      conds.add("t.created_on >= ?");
      args.add(beginDate);
    }

    if (StringUtils.isNotEmpty(endDate)) {
      conds.add("t.created_on <= ?");
      args.add(endDate);
    }

    if (locationId != null) {
      conds.add("t.stock_location = ?");
      args.add(locationId);
    }

    if (productId != null) {
      conds.add("t.product = ?");
      args.add(productId);
    }

    String cmd =
        "select "
            + "  stock.name location_name, stock.id location_id, p.id product_id, p.code product_code, "
            + "  p.name product_name, sum(t.in_qty) inQty, sum(t.out_qty) outQty,sum(delta) as delta, p.description as product_desc from stock_stock_in_out t "
            + "inner join base_product p on t.product = p.id "
            + "inner join stock_stock_location stock on t.stock_location = stock.id "
            + "%s"
            + " group by stock.name,p.name,p.code,p.id,stock.id";

    if (CollectionUtils.isNotEmpty(conds)) {
      cmd = String.format(cmd, String.format(" where %s ", join(conds, " and ")));
    } else {
      cmd = String.format(cmd, "");
    }
    Query query = JPA.em().createNativeQuery(cmd);

    int len = args.size();

    for (int i = 0; i < len; i++) {
      query.setParameter(i + 1, args.get(i));
    }

    @SuppressWarnings("unchecked")
    List<Object[]> results = query.getResultList();

    List<Map<String, Object>> mapResult = new ArrayList<>();

    for (Object[] rowValues : results) {
      Map<String, Object> mapValue = new LinkedHashMap<>();
      mapValue.put("location_name", rowValues[0]);
      mapValue.put("location_id", rowValues[1]);
      mapValue.put("product_id", rowValues[2]);
      mapValue.put("product_code", rowValues[3]);
      mapValue.put("product_name", rowValues[4]);
      mapValue.put("inQty", rowValues[5]);
      mapValue.put("outQty", rowValues[6]);
      mapValue.put("delta", rowValues[7]);
      mapValue.put("product_desc", rowValues[8]);
      mapResult.add(mapValue);
    }

    return mapResult;
  }

  private String join(List<?> exps, String joiner) {
    StringBuffer sb = new StringBuffer();
    Iterator<?> ite = exps.iterator();
    if (ite.hasNext()) {
      sb.append(ite.next());
    }
    while (ite.hasNext()) {
      sb.append(joiner).append(ite.next());
    }

    return sb.toString();
  }
}
